//
//  MainTabbarVC.m
//  Cunli
//
//  Created by lilubin on 15/6/9.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "MainTabbarVC.h"
#import "AboutAppVC.h"
#import "BaseNavCtrl.h"
#import "ChatListViewController.h"
#import "CunWuContentViewController.h"
#import "DailyTalkVC.h"
#import "LawMetrailTableVC.h"
#import "LawListsTableVC.h"
#import "LinLiViewController.h"
//#import "LoginVC_new.h"
#import "MyDataService.h"
#import "NewDetailController.h"
#import "NewsTableViewController.h"
#import "NSString+MD5.h"
#import "PeopleServiceHomeVC.h"
#import "PortraitBtn.h"
#import "SearchInfoViewController.h"
#import "SwipableViewController.h"
#import "StudyHomeTableVC.h"
#import "TongZhiDetailViewController.h"
#import "weatherBtn.h"
#import "UserInfoDetail.h"
#import "UIViewController+MMDrawerController.h"
#import "UIColor+expanded.h"
#import "User.h"
#import "RKSwipeBetweenViewControllers.h"
//环信头文件
#import "CallViewController.h"
#import "EMCDDeviceManager.h"
#import "ChatViewController.h"
#import "UMessage.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define KNOTIFICATIONJUMP @"notificationjump"
#define KCLLOGINOUT @"loginout"

//两次提示的默认间隔
static const CGFloat kDefaultPlaySoundInterval = 3.0;
static NSString *kMessageType = @"MessageType";
static NSString *kConversationChatter = @"ConversationChatter";
static NSString *kGroupName = @"GroupName";

@interface MainTabbarVC ()<UIAlertViewDelegate, IChatManagerDelegate, EMCallManagerDelegate>
{
    NSInteger oldSelectedTag; //用来记录上一个点击的按钮
    NSMutableArray *userArray;
}

@property (strong, nonatomic) NSDate *lastPlaySoundDate;

@end

@implementation MainTabbarVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self registerNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callOutWithChatter:) name:@"callOutWithChatter" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callControllerClose:) name:@"callControllerClose" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToNotificationViewController:) name:KNOTIFICATIONJUMP object:nil];
    
    [self createTabbar];
    [self setUpItem];
    //获取未读消息，用于tabbar显示未读数
    [[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:NO];
    [self removeEmptyConversationsFromDB];
    [self setupUnreadMessageCount];
    
    //    [self createTabbarButton];
}

- (void)callControllerClose:(NSNotification *)notification
{
    //    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    //    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    //    [audioSession setActive:YES error:nil];
    
    [[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
}

- (BOOL)canRecord
{
    
    __block BOOL bCanRecord = YES;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
    {
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                bCanRecord = granted;
            }];
        }
    }
    
    if (!bCanRecord) {
        UIAlertView * alt = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"setting.microphoneNoAuthority", @"No microphone permissions") message:NSLocalizedString(@"setting.microphoneAuthority", @"Please open in \"Setting\"-\"Privacy\"-\"Microphone\".") delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"ok", @"OK"), nil];
        [alt show];
    }
    
    return bCanRecord;
}
//掉线重连
- (void)willAutoReconnect{
    [self hideHud];
    [self showHint:NSLocalizedString(@"reconnection.ongoing", @"reconnecting...")];
}

- (void)didAutoReconnectFinishedWithError:(NSError *)error{
    [self hideHud];
    if (error) {
        [self showHint:NSLocalizedString(@"reconnection.fail", @"reconnection failure, later will continue to reconnection")];
    }else{
        [self showHint:NSLocalizedString(@"reconnection.success", @"reconnection successful！")];
    }
}

- (void)callSessionStatusChanged:(EMCallSession *)callSession changeReason:(EMCallStatusChangedReason)reason error:(EMError *)error
{
    if (callSession.status == eCallSessionStatusConnected)
    {
        EMError *error = nil;
        do {
            BOOL isShowPicker = [[[NSUserDefaults standardUserDefaults] objectForKey:@"isShowPicker"] boolValue];
            if (isShowPicker) {
                error = [EMError errorWithCode:EMErrorInitFailure andDescription:NSLocalizedString(@"call.initFailed", @"Establish call failure")];
                break;
            }
            
            if (![self canRecord]) {
                error = [EMError errorWithCode:EMErrorInitFailure andDescription:NSLocalizedString(@"call.initFailed", @"Establish call failure")];
                break;
            }
            
            //在后台时
            if(callSession.type == eCallSessionTypeVideo && ([[UIApplication sharedApplication] applicationState] != UIApplicationStateActive || ![CallViewController canVideo])){
                
                [self  showNotificationWithChatType:@"视频通话" andChaterName:callSession.sessionChatter];
            }
            
            if(callSession.type == eCallSessionTypeAudio && ([[UIApplication sharedApplication] applicationState] != UIApplicationStateActive || ![CallViewController canVideo])){
                
                [self  showNotificationWithChatType:@"语音通话" andChaterName:callSession.sessionChatter];
            }
            
            if (!isShowPicker){
                [[EaseMob sharedInstance].callManager removeDelegate:self];
                CallViewController *callController = [[CallViewController alloc] initWithSession:callSession isIncoming:YES];
                callController.userInfoArray=userArray;
                callController.modalPresentationStyle = UIModalPresentationOverFullScreen;
                [self presentViewController:callController animated:NO completion:nil];
                if ([self.navigationController.topViewController isKindOfClass:[ChatViewController class]])
                {
                    ChatViewController *chatVc = (ChatViewController *)self.navigationController.topViewController;
                    chatVc.isInvisible = YES;
                }
            }
        } while (0);
        
        if (error) {
            [[EaseMob sharedInstance].callManager asyncEndCall:callSession.sessionId reason:eCallReasonHangup];
            return;
        }
    }
}

- (void)callOutWithChatter:(NSNotification *)notification
{
    id object = notification.object;
    if ([object isKindOfClass:[NSDictionary class]]) {
        if (![self canRecord]) {
            return;
        }
        
        EMError *error = nil;
        NSString *chatter = [object objectForKey:@"chatter"];
        
        EMCallSessionType type = [[object objectForKey:@"type"] intValue];
        EMCallSession *callSession = nil;
        if (type == eCallSessionTypeAudio) {
            callSession = [[EaseMob sharedInstance].callManager asyncMakeVoiceCall:chatter timeout:50 error:&error];
        }
        else if (type == eCallSessionTypeVideo){
            if (![CallViewController canVideo]) {
                return;
            }
            callSession = [[EaseMob sharedInstance].callManager asyncMakeVideoCall:chatter timeout:50 error:&error];
        }
        
        if (callSession && !error) {
            [[EaseMob sharedInstance].callManager removeDelegate:self];
            CallViewController *callController = [[CallViewController alloc] initWithSession:callSession isIncoming:NO];
            //callController.userInfoArray=userArray;
            callController.modalPresentationStyle = UIModalPresentationOverFullScreen;
            [self presentViewController:callController animated:NO completion:nil];
        }
        
        if (error) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", @"error") message:error.description delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
            [alertView show];
        }
    }
}


-(void)registerNotifications
{
    [self unregisterNotifications];
    
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    [[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
}

-(void)unregisterNotifications
{
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
    [[EaseMob sharedInstance].callManager removeDelegate:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

//创建tabbar控制的字控制器
- (void)createTabbar
{
#pragma - mark 生成资讯控制器
    NSMutableArray *infoVCArray = [NSMutableArray arrayWithCapacity:5];
    NSArray *infoTitles = @[@"乡贤推介", @"外面事", @"周围事", @"村里事", @"每日谈"];
    //热点
    NewsTableViewController *vcHome = [[NewsTableViewController alloc] initWithNewsListType:NewsListTypeCountryTwitter];
    vcHome.view.backgroundColor = [UIColor whiteColor];
    [infoVCArray addObject:vcHome];
    //外面事
    NewsTableViewController *vc2 = [[NewsTableViewController alloc] initWithNewsListType:NewsListTypeOutside];
    vc2.view.backgroundColor = [UIColor whiteColor];
    [infoVCArray addObject:vc2];
    //周围的事
    NewsTableViewController *vc1 = [[NewsTableViewController alloc] initWithNewsListType:NewsListTypeSurroundings];
    vc1.view.backgroundColor = [UIColor whiteColor];
    [infoVCArray addObject:vc1];
    //身边事（村里事）
    NewsTableViewController *vc3 = [[NewsTableViewController alloc] initWithNewsListType:NewsListTypeAround];
    vc3.view.backgroundColor = [UIColor whiteColor];
    [infoVCArray addObject:vc3];
    //每日谈
    DailyTalkVC *vc4 = [[DailyTalkVC alloc] initWithStyle:UITableViewStyleGrouped];
    vc4.view.backgroundColor = [UIColor whiteColor];
    [infoVCArray addObject:vc4];
    //添加swipableviewcontroller
    SwipableViewController *informationPartSwipable = [[SwipableViewController alloc] initWithTitle:[Login curLoginBaseUser].areaname andSubTitles:infoTitles andControllers:infoVCArray underTabbar:YES];
    [informationPartSwipable scrollToViewAtIndex:1];
    
    [self setUpChildVc:informationPartSwipable title:@"资讯" image:@"tabbar_00_unsel" selectedImage:@"tabbar_00_sel"];
    
#pragma - mark   学习控制器部分
    NSMutableArray *learnVCArray = [NSMutableArray arrayWithCapacity:4];
    NSArray *learnTitles = @[@"推荐", @"法律法规", @"普法教材", @"普法讲堂"];
    
    StudyHomeTableVC *studyVC1TJ = [[StudyHomeTableVC alloc] init];
    [learnVCArray addObject:studyVC1TJ];
    
    LawListsTableVC *lawList = [[LawListsTableVC alloc] init];
    [learnVCArray addObject:lawList];
    
    LawMetrailTableVC *studyVC3PFJC = [[LawMetrailTableVC alloc] initWithLearnTableListType:LearnTableViewMetrail];
    [learnVCArray addObject:studyVC3PFJC];
    
    LawMetrailTableVC *studyVC4PFJT = [[LawMetrailTableVC alloc] initWithLearnTableListType:LearnTableViewClassroom];
    [learnVCArray addObject:studyVC4PFJT];
    
    SwipableViewController *learnPartSwipable = [[SwipableViewController alloc] initWithTitle:@"学习" andSubTitles:learnTitles andControllers:learnVCArray underTabbar:YES];
    
    //    BaseNavCtrl *learnNavVC = [self addNavigationItemForLearnViewController:learnPartSwipable];
    //    [barCtrls addObject:learnNavVC];
    [self setUpChildVc:learnPartSwipable title:@"学习" image:@"tabbar_01_unsel" selectedImage:@"tabbar_01_sel"];
    
    
#pragma - mark   村友控制器部分
    ChatListViewController *ChatListVC=[[ChatListViewController alloc] init];
    //    BaseNavCtrl *serNAV = [self addNavigationItemForViewController:ChatListVC];
    [self setUpChildVc:ChatListVC title:@"村友" image:@"tabbar_02_unsel" selectedImage:@"tabbar_02_sel"];
    
#pragma - mark   乡情部分
    
    LinLiViewController *villageVC=[[LinLiViewController alloc]initWithmyType:1];
    LinLiViewController *countyVC=[[LinLiViewController alloc]initWithmyType:2];
    LinLiViewController *cityVC=[[LinLiViewController alloc]initWithmyType:3];
    
    RKSwipeBetweenViewControllers *villageNav = [RKSwipeBetweenViewControllers newSwipeBetweenViewControllers];
    [villageNav.viewControllerArray addObjectsFromArray:@[villageVC,countyVC,cityVC]];
    [self setNavVc:villageNav title:@"乡情" image:@"tabbar_03_unsel" selectedImage:@"tabbar_03_sel"];

#pragma - mark   便民控制器部分
    PeopleServiceHomeVC *peopleServiceVC = [[PeopleServiceHomeVC alloc] init];
    peopleServiceVC.title = @"便民";
    [self setUpChildVc:peopleServiceVC title:@"便民" image:@"tabbar_04_unsel" selectedImage:@"tabbar_04_sel"];
}

- (void)setUpItem
{
    // UIControlStateNormal情况下的文字属性
    NSMutableDictionary *normalAtrrs = [NSMutableDictionary dictionary];
    // 文字颜色
    normalAtrrs[NSForegroundColorAttributeName] = [UIColor grayColor];
    
    // UIControlStateSelected情况的文字属性
    NSMutableDictionary *selectedAtrrs = [NSMutableDictionary dictionary];
    // 文字颜色
    selectedAtrrs[NSForegroundColorAttributeName] = [UIColor colorWithHexString:@"0xdb5966"];
    
    // 统一给所有的UITabBatItem设置文字属性
    // 只有后面带有UI_APPEARANCE_SELECTOR方法的才可以通过appearance来设置
    UITabBarItem *item = [UITabBarItem appearance];
    [item setTitleTextAttributes:normalAtrrs forState:UIControlStateNormal];
    [item setTitleTextAttributes:selectedAtrrs forState:UIControlStateSelected];
    
    [self.tabBar setBackgroundColor:[UIColor whiteColor]];
    self.tabBar.opaque = YES;
}


- (void)setUpChildVc:(UIViewController *)vc title:(NSString *)title image:(NSString *)image selectedImage:(NSString *)selectedImage
{
    // 包装一个导航控制器
    BaseNavCtrl *nav = [[BaseNavCtrl alloc] initWithRootViewController:vc];
    
    if ([title isEqualToString:@"资讯"] || [title isEqualToString:@"学习"]) {
        if ([title isEqualToString:@"资讯"]) {
            
            PortraitBtn *portraitBtn = [[PortraitBtn alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
            [portraitBtn.layer setCornerRadius:20];
            portraitBtn.layer.masksToBounds = YES;
            //        portraitBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -40, 0, 0); 通过这种方法来设置时，并不能生效
            [portraitBtn addTarget:self action:@selector(popSideMenu) forControlEvents:UIControlEventTouchUpInside];
            UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:portraitBtn];
            UIBarButtonItem *flexSpacer_left = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
            flexSpacer_left.width = flexSpacer_left.width-10;
            [vc.navigationItem setLeftBarButtonItems:[NSArray arrayWithObjects:flexSpacer_left, leftBarItem, nil]];
        }

        /*
        weatherBtn *weaBtn = [[weatherBtn alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        weaBtn.backgroundColor = [UIColor clearColor];
        UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:weaBtn];
        UIBarButtonItem *flexSpacer_right = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
        flexSpacer_right.width = flexSpacer_right.width-10;
        [vc.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:flexSpacer_right, rightBarItem, nil]];
         */
        
        UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [searchBtn setImage:[UIImage imageNamed:@"nav_right_search"] forState:UIControlStateNormal];
        [searchBtn setFrame:CGRectMake(0, 7, 20, 20)];
        [searchBtn addTarget:self action:@selector(jumpToSearchVC) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:searchBtn];
        vc.navigationItem.rightBarButtonItem = rightBarItem;
    
    }
    /*
    else if([title isEqualToString:@"学习"])
    {
    }
     */
    [self addChildViewController:nav];
    
    // 设置子控制器的tabBarItem
    nav.tabBarItem.title = title;
    nav.tabBarItem.image = [UIImage imageNamed:image];
    UIImage *selImg = [UIImage imageNamed:selectedImage];
    selImg = [selImg imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    nav.tabBarItem.selectedImage = selImg;
}

- (void)setNavVc:(UINavigationController *)nav title:(NSString *)title image:(NSString *)image selectedImage:(NSString *)selectedImage{
    
    [self addChildViewController:nav];
    
    // 设置子控制器的tabBarItem
    nav.tabBarItem.title = title;
    nav.tabBarItem.image = [UIImage imageNamed:image];
    UIImage *selImg = [UIImage imageNamed:selectedImage];
    selImg = [selImg imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    nav.tabBarItem.selectedImage = selImg;
}

- (void)popSideMenu
{
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:NULL];
}

- (void)jumpToSearchVC
{
    BaseNavCtrl *selectedVC = (BaseNavCtrl *)self.selectedViewController;
    SearchInfoViewController *searchVC = [[SearchInfoViewController alloc] init];
    searchVC.hidesBottomBarWhenPushed = YES;
    [selectedVC pushViewController:searchVC animated:YES];
}

#pragma - mark 异地登陆

- (void)didLoginFromOtherDevice
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"您的账号已在其他手机上登录。如非本人操作，则密码可能已泄露，建议修改密码。" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    alert.tag = 1005;
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 1005) {
        
        [Config removeAutoLogin];
        [Config saveAutoLogin:NO];
        [Config removeLogin];
        [self loginout];
        
    }
}

- (void)loginout
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"tongXunLuArray"];
    NSArray *areaidsArray = [[Config getOwnAreaids] componentsSeparatedByString:@","];
    [UMessage removeTag:areaidsArray response:^(id responseObject, NSInteger remain, NSError *error) {
        //NSLog(@"添加APSN失败:%@", error.userInfo);
    }];
    //      [UMessage unregisterForRemoteNotifications];
    EMError *error = nil;
    NSDictionary *info = [[EaseMob sharedInstance].chatManager logoffWithUnbindDeviceToken:YES error:&error];
    if (!error && info) {
        NSLog(@">>>>>>>退出成功");
        [[NSNotificationCenter defaultCenter] postNotificationName:KCLLOGINOUT object:nil];
    }
    /*
    LoginVC_new *loginVC = [[LoginVC_new alloc] init];
    loginVC.netCheck = @"";
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    keyWindow.rootViewController = loginVC;
    [keyWindow makeKeyAndVisible];
     */
}


#pragma mark - 环信消息回调
// 收到消息回调
-(void)didReceiveMessage:(EMMessage *)message
{
    BOOL needShowNotification = (message.messageType != eMessageTypeChat) ? [self needShowNotification:message.conversationChatter] : YES;
    if (needShowNotification) {
#if !TARGET_IPHONE_SIMULATOR
        
        BOOL isAppActivity = [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
        if (!isAppActivity) {
            [self showNotificationWithMessage:message];
        }else {
            [self playSoundAndVibration];
        }
#endif
    }
}

- (BOOL)needShowNotification:(NSString *)fromChatter
{
    BOOL ret = YES;
    NSArray *igGroupIds = [[EaseMob sharedInstance].chatManager ignoredGroupIds];
    for (NSString *str in igGroupIds) {
        if ([str isEqualToString:fromChatter]) {
            ret = NO;
            break;
        }
    }
    
    return ret;
}

- (void)playSoundAndVibration{
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        //如果距离上次响铃和震动时间太短, 则跳过响铃
        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
        return;
    }
    
    //保存最后一次响铃时间
    self.lastPlaySoundDate = [NSDate date];
    
    // 收到消息时，播放音频
    [[EMCDDeviceManager sharedInstance] playNewMessageSound];
    // 收到消息时，震动
    [[EMCDDeviceManager sharedInstance] playVibration];
}

- (void)showNotificationWithMessage:(EMMessage *)message
{
    EMPushNotificationOptions *options = [[EaseMob sharedInstance].chatManager pushNotificationOptions];
    //发送本地推送
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate date]; //触发通知的时间
    
    if (options.displayStyle == ePushNotificationDisplayStyle_messageSummary) {
        id<IEMMessageBody> messageBody = [message.messageBodies firstObject];
        NSString *messageStr = nil;
        switch (messageBody.messageBodyType) {
            case eMessageBodyType_Text:
            {
                messageStr = ((EMTextMessageBody *)messageBody).text;
                //NSLog(@"######%@#####",messageStr);
            }
                break;
            case eMessageBodyType_Image:
            {
                messageStr = NSLocalizedString(@"message.image", @"Image");
            }
                break;
            case eMessageBodyType_Location:
            {
                messageStr = NSLocalizedString(@"message.location", @"Location");
            }
                break;
            case eMessageBodyType_Voice:
            {
                messageStr = NSLocalizedString(@"message.voice", @"Voice");
            }
                break;
            case eMessageBodyType_Video:{
                messageStr = NSLocalizedString(@"message.vidio", @"Vidio");
            }
                break;
            default:
                break;
        }
        
        NSString *title = message.from;
        if (message.messageType == eMessageTypeGroupChat) {
            NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
            for (EMGroup *group in groupArray) {
                if ([group.groupId isEqualToString:message.conversationChatter]) {
                    title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, group.groupSubject];
                    break;
                }
            }
        }
        else if (message.messageType == eMessageTypeChatRoom)
        {
            NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
            NSString *key = [NSString stringWithFormat:@"OnceJoinedChatrooms_%@", [[[EaseMob sharedInstance].chatManager loginInfo] objectForKey:@"username" ]];
            NSMutableDictionary *chatrooms = [NSMutableDictionary dictionaryWithDictionary:[ud objectForKey:key]];
            NSString *chatroomName = [chatrooms objectForKey:message.conversationChatter];
            if (chatroomName)
            {
                title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, chatroomName];
            }
        }
        
        notification.alertBody = [NSString stringWithFormat:@"%@:%@", title, messageStr];
    }
    else{
        notification.alertBody = NSLocalizedString(@"receiveMessage", @"you have a new message");
    }
    
#warning 去掉注释会显示[本地]开头, 方便在开发中区分是否为本地推送
    //notification.alertBody = [[NSString alloc] initWithFormat:@"[本地]%@", notification.alertBody];
    notification.alertAction = NSLocalizedString(@"open", @"Open");
    notification.timeZone = [NSTimeZone defaultTimeZone];
    notification.soundName = UILocalNotificationDefaultSoundName;
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    [userInfo setObject:[NSNumber numberWithInt:message.messageType] forKey:kMessageType];
    [userInfo setObject:message.conversationChatter forKey:kConversationChatter];
    notification.userInfo = userInfo;
    
    NSLog(@">>>>>>>>>>>%@",userInfo);
    //发送通知
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    UIApplication *application = [UIApplication sharedApplication];
    application.applicationIconBadgeNumber += 1;
}

#pragma mark - 通过点击推送消息进入后执行的方法
- (void)pushToNotificationViewController:(NSNotification *)notification
{
    NSDictionary *notificationDic = (NSDictionary *)notification.object;
    NSLog(@"notification dic:%@", notificationDic);
    
    BaseNavCtrl *selectedVC = (BaseNavCtrl *)self.selectedViewController;
    
    if (notificationDic[@"custom"] == nil) {
        return;
    }
    else if([notificationDic[@"custom"] isEqualToString:@"t"])
    {
        TongZhiDetailViewController *detailVC = [[TongZhiDetailViewController alloc] init];
        detailVC.itemid=[notificationDic[@"itemid"] intValue];
        detailVC.type=[notificationDic[@"type"] intValue];
        detailVC.hidesBottomBarWhenPushed=YES;
        [selectedVC pushViewController:detailVC animated:YES];
    }
    else if([notificationDic[@"custom"] isEqualToString:@"cwgk"])
    {
        CunWuContentViewController *affairsVC = [[CunWuContentViewController alloc] init];
        affairsVC.itemid = [notificationDic objectForKey:@"itemid"];
        affairsVC.hidesBottomBarWhenPushed = YES;
        [selectedVC pushViewController:affairsVC animated:YES];
    }
    else if([notificationDic[@"custom"] isEqualToString:@"news"])
    {
        NewDetailController *newsDetailVC = [[NewDetailController alloc] init];
        newsDetailVC.itemID = notificationDic[@"itemid"];
        newsDetailVC.hidesBottomBarWhenPushed = YES;
        [selectedVC pushViewController:newsDetailVC animated:YES];
    }
    
}

// 统计未读消息数
-(void)setupUnreadMessageCount
{
    NSArray *conversations = [[[EaseMob sharedInstance] chatManager] conversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }
    NSLog(@"收到消息%ld条",unreadCount);
    UIViewController *chatVC=[self.viewControllers objectAtIndex:2];
    if (chatVC) {
        if (unreadCount > 0) {
            chatVC.tabBarItem.badgeValue = [NSString stringWithFormat:@"%i",(int)unreadCount];
        }else{
            chatVC.tabBarItem.badgeValue = nil;
        }
    }
}

#pragma mark - IChatManagerDelegate 消息变化

- (void)didUpdateConversationList:(NSArray *)conversationList
{
    [self setupUnreadMessageCount];
}

// 未读消息数量变化回调
-(void)didUnreadMessagesCountChanged
{
    [self setupUnreadMessageCount];
}

- (void)didFinishedReceiveOfflineMessages
{
    [self setupUnreadMessageCount];
}

- (void)removeEmptyConversationsFromDB
{
    NSArray *conversations = [[EaseMob sharedInstance].chatManager conversations];
    NSMutableArray *needRemoveConversations;
    for (EMConversation *conversation in conversations) {
        if (!conversation.latestMessage || (conversation.conversationType == eConversationTypeChatRoom)) {
            if (!needRemoveConversations) {
                needRemoveConversations = [[NSMutableArray alloc] initWithCapacity:0];
            }
            [needRemoveConversations addObject:conversation.chatter];
        }
    }
    
    if (needRemoveConversations && needRemoveConversations.count > 0) {
        [[EaseMob sharedInstance].chatManager removeConversationsByChatters:needRemoveConversations
                                                             deleteMessages:YES
                                                                append2Chat:YES];
    }
    
}

- (void)dealloc
{
    [self unregisterNotifications];
}

- (void)showNotificationWithChatType:(NSString *)chatType andChaterName:(NSString *)chaterName
{
    //发送本地推送
    NSString *remindString;
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults]objectForKey:@"huanXinInfo"];
    NSString *realNameString=[dic objectForKey:[NSString stringWithFormat:@"%@name",chaterName]];
    if (realNameString) {
        remindString=[NSString stringWithFormat:@"%@请求%@",realNameString,chatType];
    }else{
        remindString=[NSString stringWithFormat:@"您有一个%@",chatType];
    }
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate date]; //触发通知的时间
    notification.alertBody = remindString;
    notification.alertAction = NSLocalizedString(@"open", @"Open");
    notification.timeZone = [NSTimeZone defaultTimeZone];
    notification.soundName = UILocalNotificationDefaultSoundName;
    notification.hasAction=YES;
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

@end
